package com.chatgpt.api.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chatgpt.api.conf.ChatPlusConfig;
import com.chatgpt.api.service.UserService;
import com.chatgpt.api.service.entity.User;
import com.chatgpt.api.service.mapper.UserMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * User service implementation
 *
 * @author yangjian
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final ChatPlusConfig appConfig;

    public UserServiceImpl(ChatPlusConfig appConfig) {
        this.appConfig = appConfig;
    }


    @Override
    public String genToken(int userId) {
        Date now = new Date();
        Date expiration = new Date(now.getTime() + appConfig.getSession().getExpiredTime());
        return Jwts.builder()
                .setSubject(String.valueOf(userId))
                .setIssuedAt(now)
                .setExpiration(expiration)
                .signWith(SignatureAlgorithm.HS256,appConfig.getSession().getSecretKey())
                .compact();
    }

    @Override
    public User getUserFromToken(String token) {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(appConfig.getSession().getSecretKey()).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        int userId = Integer.parseInt(claims.getSubject());
        return getById(userId);

    }

}
